﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Atmk.WaterMeter.MIS.Base;
using Atmk.WaterMeter.MIS.Common;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.CT_NBIoT;
using Atmk.WaterMeter.MIS.Commons.Utils;
using Atmk.WaterMeter.MIS.Entities.Enums;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace Atmk.WaterMeter.MIS.Controllers.CTNBIoT
{
    /// <summary>
    /// 操作电信NB平台对外接口
    /// 测试电信平台获取数据及验证指令(标准)
    /// 维护抄表系统水表数据与NB平台的对接(扩展-未实现)
    /// </summary>
    [Authorize]
    public class CT_NBIoT_PlatformController : BaseApiController
    {
        private readonly ICT_PlatformDevideManageLogic _ctPlatformDevideManageLogic;
        private readonly ICT_PlatformDeviceInfoLogic _ctPlatformDeviceInfoLogic;
        private static ILogger<CT_NBIoT_PlatformController> _Logger;

        /// <inheritdoc />
        public CT_NBIoT_PlatformController(
            ICT_PlatformDevideManageLogic ctPlatformDevideManageLogic,
            ICT_PlatformDeviceInfoLogic ctPlatformDeviceInfoLogic,
            ILogger<CT_NBIoT_PlatformController> logger
        )
        {
            _ctPlatformDeviceInfoLogic = ctPlatformDeviceInfoLogic;
            _ctPlatformDevideManageLogic = ctPlatformDevideManageLogic;
            _Logger = logger;
        }

        /// <summary>
        /// 注册设备并返回设备id
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/tp/ct/mg/device")]
        public async Task<IActionResult> RegistDevice([FromBody] dynamic obj)
        {
            string imei = obj.imei.ToString();
            string model = obj.model.ToString();
            string name = obj.number.ToString();
            var res = await _ctPlatformDevideManageLogic.AddDevice(imei, model, name);
            return res.Success
                ? Ok(new {errcode = 0, msg = "注册成功", data = new {deviceId = res.Message}})
                : Ok(new {errcode = 1, msg = $"注册失败:{res.ErrorMessage}"});
        }

        /// <summary>
        /// 删除设备并返回设备id
        /// </summary>
        /// <param name="deviceId"></param>
        /// <returns></returns>
        [HttpDelete("/api/{X-Version}/tp/ct/mg/device/{deviceId}")]
        public async Task<IActionResult> DeleteDevice(string deviceId)
        {
            var res = await _ctPlatformDevideManageLogic.DeleteDevice(deviceId);
            return res.Success
                ? Ok(new {errcode = 0, msg = "删除成功"})
                : Ok(new {errcode = 1, msg = $"删除失败:{res.ErrorMessage}"});
        }

        /// <summary>
        /// 读取所有设备
        /// </summary>
        /// <returns></returns>
        [HttpGet("/api/{X-Version}/tp/ct/mg/devices")]
        public async Task<IActionResult> GetDevices()
        {
            try
            {
                var res = await _ctPlatformDevideManageLogic.GetDevices();
                var data = new
                {
                    res.pageNo,
                    res.pageSize,
                    res.totalCount,
                    devices = res.devices.
                    Select(d => new
                        {
                            d.deviceId, d.deviceInfo.name, imei = d.deviceInfo.nodeId
                        })
                    .ToList()
                };
                return Ok(new {errcode = 0, msg = "查询成功", data});
            }
            catch (Exception e)
            {
                _Logger.LogError(e.Message, e);
                return Ok(new {errcode = 1, msg = $"查询失败:{e.Message}"});
            }
        }
        //读取设备历史数据

        /// <summary>
        /// 读取设备最新数据
        /// </summary>
        /// <param name="deviceId"></param>
        /// <returns></returns>
        [HttpGet("/api/{X-Version}/tp/ct/rd/record/{deviceId}")]
        public async Task<IActionResult> ReadNewDeviceInfo(string deviceId)
        {
            try
            {
                var res = await _ctPlatformDeviceInfoLogic.ReadFirstMeterRecord(deviceId);
                //记录小时冻结数据
                var data = new
                {
                    deviceId,
                    reading = res.Value,
                    valve = res.ValveState.ToString(),
                    voltage = res.Voltage,
                    historys = res.Value24,
                    readTime = res.ReadTime.ToString("yyyy-MM-dd HH:mm:ss")
                };
                return Ok(new {errcode = 0, msg = "注册成功", data});
            }
            catch (Exception e)
            {
                _Logger.LogError(e.Message, e);
                return Ok(new {errcode = 1, msg = $"读取失败:{e.Message}"});
            }
        }

      
        /// <summary>
        /// 下发开关阀指令  valve = 1:开阀 0:关阀
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/tp/ct/cm/valve")]
        public async Task<IActionResult> SetValveState([FromBody] dynamic obj)
        {
            //Closed Opening
            string deviceId = obj.deviceId.ToString();
            string valve = obj.valve.ToString();
            var valuState = valve == "1" ? ValveState.Opening : ValveState.Closed;
            var res = await _ctPlatformDeviceInfoLogic.SetValveState(deviceId, valuState);
            return res.Success
                ? Ok(new {errcode = 0, msg = "指令下发成功",data = res.ResJObject})
                : Ok(new {errcode = 1, msg = $"指令下发失败:{res.ErrorMessage}", data = res.ResJObject });
        }
        /// <summary>
        /// 下发查询冻结数据指令 freezingType 0 24小时冻结，1 30日冻结，2 24月冻结
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/tp/ct/cm/freezing")]
        public async Task<IActionResult> SetFreezingData([FromBody] dynamic obj)
        {
            string deviceId = obj.deviceId.ToString();
            if(!int.TryParse(obj.freezingType.ToString(),out int freezingType))
            {
                return Ok(new
                {
                    errcode = 2,
                    msg = "冻结数据类型参数错误,不是数字"
                });
            }
            if (freezingType < 0 || freezingType > 2)
                return Ok(new { errcode = 2, msg = "冻结数据类型参数错误,不在取值范围内" });
            var res = await _ctPlatformDeviceInfoLogic.SetFreezingDataCommand(deviceId, freezingType);
            return res.Success
                ? Ok(new { errcode = 0, msg = "指令下发成功", data = res.ResJObject })
                : Ok(new { errcode = 1, msg = $"指令下发失败:{res.ErrorMessage}", data = res.ResJObject });
        }
        #region 需要南向数据返回的

        /// <summary>
        /// 读取电信平台存储的最新的对应冻结类型的数据
        /// </summary>
        /// <param name="deviceId"></param>
        /// <param name="freezingType">0 24小时冻结，1 30日冻结，2 24月冻结</param>
        /// <returns></returns>
        [HttpGet("/api/{X-Version}/tp/ct/rd/freezing")]
        public async Task<IActionResult> ReadNewFreezingData(string deviceId, int freezingType)
        {
            if (freezingType < 0 || freezingType > 2)
                return Ok(new { errcode = 2, msg = "冻结数据类型参数错误,不在取值范围内" });
            try
            {
                var res = await _ctPlatformDeviceInfoLogic.ReadNewFreezData(deviceId, freezingType);
                var data = new
                {
                    res.deviceId,
                    res.freezetype,
                    res.freezedata,
                    time = res.time.ToString("yyyy-MM-dd HH:mm:ss")
                };
                return Ok(new { errcode = 0, msg = "查询成功", data });
            }
            catch (Exception e)
            {
                _Logger.LogError(e.Message,e);
                return Ok(new { errcode = 1, msg = $"查询失败{e.Message}"});
            }
          
          
        }


        #endregion

        //读取冻结数据


        ///// <summary>
        /////  批量 下发开阀指令  valve = 1:开阀 0:关阀
        ///// </summary>

        //public async Task<IActionResult> BatchOpenValve()
        //{
        //    //Closed Opening
        //    string[] deviceIds = { "8a61a230-f208-4421-ad40-4bfb2259c9dd", "5a5832ea-871d-4169-97f4-8c964fc74f09" };
        //    var res = await _ctPlatformDeviceInfoLogic.BatchOpenValve(deviceIds);
        //    return res.Success
        //        ? Ok(new { errcode = 0, msg = "指令下发成功", data = res.ResJObject })
        //        : Ok(new { errcode = 1, msg = $"指令下发失败:{res.ErrorMessage}", data = res.ResJObject });
        //}
    }
}